package com.android;

import android.content.Context;
import android.content.SharedPreferences;


public class SharedPreUtil {
    public static final String CACHE = "robut_cache";
    public static final String DOWNLOAD_ID = "download_id";

    private static SharedPreUtil instance;
    private SharedPreferences sp;

    private SharedPreUtil(Context context) {
        sp = context.getApplicationContext().getSharedPreferences(CACHE, Context.MODE_PRIVATE);
    }

    public static SharedPreUtil getInstance(Context context) {
        if (null == instance) {
            synchronized (SharedPreUtil.class) {
                if (null == instance) {
                    instance = new SharedPreUtil(context);
                }
            }
        }
        return instance;
    }

    /**
     * SharedPreferences通过key取值
     *
     * @param key
     * @param dfValue 默认值
     * @return
     */
    public String getValue(String key, String dfValue) {
        String value = sp.getString(key, dfValue);
        if ("null".equals(value)) {
            value = dfValue;
        }
        return value;
    }
    /**
     * SharedPreferences通过key取值
     *
     * @param key
     * @param dfValue 默认值
     * @return
     */
    public long getValue(String key, long dfValue) {
        long value = sp.getLong(key,  System.currentTimeMillis());
        if ("null".equals(value)) {
            value = dfValue;
        }
        return value;
    }
    /**
     * SharedPreferences通过key存value
     *
     * @param key
     * @param value
     */
    public void saveValue(String key, String value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.apply();
    }
    /**
     * SharedPreferences通过key存value
     *
     * @param key
     * @param value
     */
    public void saveValue(String key, long value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(key, value);
        editor.apply();
    }
    /**
     * SharedPreferences通过key取值
     *
     * @param key
     * @param dfValue 默认值
     * @return
     */
    public boolean getValue(String key, boolean dfValue) {
        boolean value = sp.getBoolean(key, dfValue);
        if ("null".equals(value)) {
            value = dfValue;
        }
        return value;
    }

    /**
     * SharedPreferences通过key存value
     *
     * @param key
     * @param value
     */
    public void saveValue(String key, boolean value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    /**
     * 清空所有数据
     */
    public void clearAllData() {
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();
    }

    /**
     * 清空所有数据
     */
    public void clearData(String key) {
        SharedPreferences.Editor editor = sp.edit();
        if (sp.contains(key)) {
            editor.remove(key);
            editor.apply();
        }
    }
}


